package com.youpai.platform.common.config;

import com.fasterxml.classmate.TypeResolver;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.schema.WildcardType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.*;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static springfox.documentation.schema.AlternateTypeRules.newRule;

/**
 * @Description: knife4j 配置文件
 * @Author:welles
 * @Date:2022/7/23
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
    /**
     * 是否启用在线接口文档
     */
    @Value("${swagger.show:true}")
    private boolean swaggerShow;

    @Resource
    private TypeResolver typeResolver;

    @Bean
    public Docket createRestApi() {
        //添加head参数-access_token
        ParameterBuilder tokenPar = new ParameterBuilder();
        ParameterBuilder appIdPar = new ParameterBuilder();
        List<Parameter> parameterList = new ArrayList<>();
        System.out.println(" ");
        tokenPar.name("w-token")
                .defaultValue("")
                .description("令牌")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false).build();
        appIdPar.name("app-id")
                .defaultValue("")
                .description("appId")
                .modelRef(new ModelRef("Integer"))
                .parameterType("header")
                .required(false).build();
        parameterList.add(tokenPar.build());
        parameterList.add(appIdPar.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swaggerShow)
                .groupName("kila 接口文档")
                .select()
                // 扫描指定包中的swagger注解
                .apis(RequestHandlerSelectors.basePackage("com.youpai.platform"))
                //扫描所有有注解的api
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(parameterList)
                .apiInfo(apiInfo())
                // 自定义规则，如果遇到DeferredResult，则把泛型类转成json
                .alternateTypeRules(
                        newRule(typeResolver.resolve(DeferredResult.class,
                                typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
                                typeResolver.resolve(WildcardType.class)));
    }

    /**
     * 基本信息
     * @return Api信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("wanxuewen-app 接口文档 APIs")
                .description("玩学问APP 接口文档")
                .termsOfServiceUrl("http://www.wanxuewen.com/")
                .contact(new Contact("kila-app", "", ""))
                .version("1.0")
                .build();
    }

    @Bean
    SecurityConfiguration security() {
        return SecurityConfigurationBuilder.builder()
                .clientId("swagger")
                .clientSecret("swagger")
                .realm("swagger")
                .appName("swagger-app")
                .scopeSeparator(",")
                .additionalQueryStringParams(null)
                .useBasicAuthenticationWithAccessCodeGrant(false)
                .build();
    }

    @Bean
    UiConfiguration uiConfig() {
        return UiConfigurationBuilder.builder()
                .deepLinking(true)
                .displayOperationId(false)
                .defaultModelsExpandDepth(1)
                .defaultModelExpandDepth(1)
                .defaultModelRendering(ModelRendering.EXAMPLE)
                .displayRequestDuration(false)
                .docExpansion(DocExpansion.NONE)
                .filter(false)
                .maxDisplayedTags(null)
                .operationsSorter(OperationsSorter.ALPHA)
                .showExtensions(false)
                .tagsSorter(TagsSorter.ALPHA)
                .validatorUrl(null)
                .build();
    }
}
